package cn.wintersun.baseweb.controller.user;


import cn.wintersun.basecommon.common.Result;
import cn.wintersun.basecommon.common.ResultCode;
import cn.wintersun.basecommon.context.BaseContext;
import cn.wintersun.baseweb.service.intrer.user.FileDateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@PreAuthorize("hasAuthority('1')")
@Slf4j
public class CommonController {


    @Autowired
    private FileDateService fileDateService;
    @Value("${file.upload-folder}")
    private String UPLOAD_FOLDER;

    @PostMapping("/upload")
    public Result<Object> uploadExcelFile(@RequestParam("file") MultipartFile file) {
        String remark = "";
        log.info("文件上传：{}",file);
//        , @RequestParam("traceId")String traceId
        if (file.isEmpty()) {
            return Result.failure(ResultCode.UPLOAD_FILE_ERROR);
        }
        try {
            //获取文件后缀
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
            if (!"xls,xlsx,xlsm,xlsb".toUpperCase().contains(suffix.toUpperCase())) {
                return Result.failure(ResultCode.UPLOAD_FORMAT_ERROR);
            }
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //利用UUID构造新文件名称
            String objectName = UUID.randomUUID() + extension;
            // 确保多级目录存在
            File filePath = new File(UPLOAD_FOLDER);
            if(!filePath.exists()){
                boolean result = filePath.mkdirs();
                if(!result){
                    return Result.failure(ResultCode.UPLOAD_PATH_ERROR);
                }
            }
            // 文件保存到本地
            Path path = Paths.get(UPLOAD_FOLDER +"/"+ objectName).normalize();
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
            int currentId = BaseContext.getCurrentId().intValue();
            fileDateService.saveFileDate(originalFilename,objectName,remark,currentId);
            return Result.ok(objectName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure(ResultCode.UPLOAD_ERROR);
        }
    }
}
